﻿using Flurl.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ImportPlcPointPosition.Controls
{
    public partial class TestToolPage : BaseUserControl
    {
        Fleck.WebSocketServer printServer;
        public TestToolPage()
        {
            InitializeComponent();
           
            if(!DesignMode)
            {
                try
                {
                    var server = new EnhancedSocketServer(4000);
                    server.OnReceiveData += Server_OnReceiveData;
                    server.Start();


                    var server2 = new EnhancedSocketServer(4001);
                    server2.OnReceiveData += Server2_OnReceiveData;
                    server2.Start();

                    // 创建服务器实例，监听本地8080端口
                    printServer = new Fleck.WebSocketServer("ws://0.0.0.0:9527/ws");
                    printServer.Start(socket => {

                        socket.OnMessage = message => {

                            //调用打印机 打印面单

                            socket.Send($"ok");
                        };
                    });
                    StartWebServer(8188);
                }
                catch (Exception ex)
                {
                    MessageError("模拟Server失败");
                }
            }
        }

        

       

        //回复面单号
        private void Server2_OnReceiveData(object sender, DataReceivedEventArgs e)
        {
            e.Response = input3.Text;
        }
        //回复托盘号
        private void Server_OnReceiveData(object sender, DataReceivedEventArgs e)
        {
            e.Response = input4.Text;
        }

        private async void btnBind_Click(object sender, EventArgs e)
        {
            try
            {
                string url = txtUrl.Text;
                Dictionary<string, string> bodys = new Dictionary<string, string>();
                bodys["ContainerNo"] = input4.Text;
                bodys["WaybillNo"] = input3.Text;
                bodys["OrderNo"] = input5.Text;
                bodys["PackageNo"] = input6.Text;
                var response = await url.PostJsonAsync(bodys);
                input7.Text = await response.GetStringAsync();
                MessageInfo("已提交");
            }
            catch (Exception)
            {

            }
        }


        public  void StartWebServer(int port)
        {
            string _url = $"http://0.0.0.0:{port}";
            var builder = WebApplication.CreateBuilder();
            // 指定监听的 URL
            builder.WebHost.UseUrls(_url);

            var _app = builder.Build();

            // 定义一个简单的 GET 请求处理程序
            _app.MapPost("/api/packagefinish", async context =>
            {
                try
                {
                    // 从请求体中读取 JSON 数据
                    var jsonData = await new StreamReader(context.Request.Body).ReadToEndAsync();

                    //EventBus.AddLog($"agvCallback，参数：  {jsonData}");
                    // 这里可以根据实际需求对 JSON 数据进行解析
                    var body = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonData);

                    // 处理接收到的数据，构建要返回的 JSON 对象
                    var responseObject = new
                    {
                        code = "0",
                        message = "successfully",
                        reqCode = body["reqCode"],
                    };

                    // 将对象序列化为 JSON 字符串
                    var responseJson = JsonConvert.SerializeObject(responseObject);

                    // 设置响应的内容类型为 JSON
                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = StatusCodes.Status200OK;
                    await context.Response.WriteAsync(responseJson);
                }
                catch (Exception ex)
                {
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;
                    await context.Response.WriteAsync($"Error: {ex.Message}");
                }
            });

            _app.Start();
        }


    }
}
